package ypmits.utils {
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.utils.Timer;

	/**
	 * @author Dave Lenz
	 */
	public class BitmapAnimator extends Sprite {

		protected var _bitmaps : Array = [];
		protected var _current : int = 0;
		protected var _timer : Timer;
		private var _speed : int;
		private var _loop : Boolean;

		
		
		public function BitmapAnimator( bitmaps : Array, speed : int = 50, loop : Boolean = false, back_and_forwards : Boolean = false ) 
		{
			if( back_and_forwards ) {
				var a : Array = ArrayTools.clone( bitmaps );
				var b : Array = ArrayTools.clone( a );
				_bitmaps = a.concat( b.reverse() );
			} else {
				_bitmaps = bitmaps;
			}
			_speed = speed;
			_loop = loop;
			
			_timer = new Timer( _speed );
			_timer.addEventListener( TimerEvent.TIMER, tHandler );
			
			for (var i : int = 0; i < _bitmaps.length; i++) 
			{
				var pict : DisplayObject = DisplayObject( _bitmaps[i] );
				pict.visible = false;
				addChild( pict );
			}
			DisplayObject( _bitmaps[0] ).visible = true;
			
			var r : Rectangle = this.getRect( this );
			graphics.beginFill( 0xFF0000, 0 );
			graphics.drawRect( r.x, r.y, r.width, r.height );
		}

		
		
		public function start() : void 
		{
			_timer.start( );
		}

		
		
		public function stop() : void 
		{
			if( _timer ) {
				_timer.removeEventListener( TimerEvent.TIMER, tHandler );
				_timer.stop( );
				_timer.reset( );
			}
		}

		
		
		private function tHandler( e : TimerEvent ) : void 
		{
			var pict : DisplayObject;
			
			pict = DisplayObject( _bitmaps[ _current ] );
			pict.visible = false;
			if( _current == _bitmaps.length - 1 ) {
				if( _loop ) {
					_current = 0;
				} else {
					stop();
				}
			} else {
				_current++;
			}
			pict = DisplayObject( _bitmaps[ _current ] );
			pict.visible = true;
		}

		
		
		/**
		 * =================
		 * GETTERS / SETTERS
		 * =================
		 */
		public function get speed() : int 
		{
			return _speed;
		}

		
		
		public function set speed(speed : int) : void {
			_speed = speed;
			
			stop( );
			start( );
		}
	}
}
